var favoriteLocationsCache = [];
var containerHTML = "";

function weatherAjax(url,container){
	// if the URL starts with http
	if(url.match('^http')){
		// assemble the YQL call
		var yqlQuery = "http://query.yahooapis.com/v1/public/yql?"+
				"q=select%20*%20from%20html%20where%20url%3D%22"+
				encodeURIComponent(url)+
				"%22&format=xml'&callback=?";
		$.getJSON(yqlQuery, 
			function weatherCallback(data){
				if(data.results[0]){
					var data = filterData(data.results[0]);
					container.html(data);
				} else {
					var errormsg = '<p>Error: Weather request timed out, try opening weather again, or try again later.</p>';
					container.html(errormsg);
				}
			}
		);
	} else {
		$.ajax({
				url: url,
				timeout:5000,
				success: function(data){
				container.html(data);
			},
			error: function(req,error){
				if(error === 'error'){error = req.statusText;}
				var errormsg = 'There was a communication error: '+error;
				container.html(errormsg);
			}
		});
	}
}

function filterData(data){
	// filter all the nasties out
	// no body tags
	data = data.replace(/<?\/body[^>]*>/g,'');
	// no linebreaks
	data = data.replace(/[\r|\n]+/g,'');
	// no comments
	data = data.replace(/<--[\S\s]*?-->/g,'');
	// no noscript blocks
	data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
	// no script blocks
	data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
	// no self closing scripts
	data = data.replace(/<script.*\/>/,'');
	// [... add as needed ...]
	data = data.replace(/(loc:(-?\d+\.?\d*),\s?(-?\d+\.?\d*))/g, '<a class="locationLink" onclick="travelToLink($2, $3, this);">$1</a>');
	return data;
}

//functions to load favorite cities into the javascript cache
function cacheFavoriteCities() {
	$.ajax({url: "/favorites/get/" + UserCharacter.currentUserCharacter().getId(),async: !0,dataType: "json",success: saveFavoritesToCache})
}

function saveFavoritesToCache(a) {
    if (a && !a.error) {
    	favoriteLocationsCache = [];
        for (var a = a.cities, c = a.length, d = 0; d < c; d++) {
            var e = {};
            e.cityName = a[d].cityName;
            e = {lat: a[d].lat,lng: a[d].lng,city: a[d].cityName};
            favoriteLocationsCache.push(e);
        }
        loadWeatherForecast();
    }
}

function weatherPostQuery() {
	//Get Weather for current location
	var queryString = truncateDigits(gCurrentClientPos.y)+","+truncateDigits(gCurrentClientPos.x)+";";
// 	for(var i in favoriteLocationsCache)
// 	{
// 		var loc = favoriteLocationsCache[i];
// 		queryString += (truncateDigits(loc.lat)+","+truncateDigits(loc.lng)+";");
// 	}
	return queryString;
}

function truncateDigits (n) {
	return Math.round(1000*n)/1000;
}

function loadWeatherForecast()
{
	if(favoriteLocationsCache.length > 0)
	{
		var weatherUrl = "http://fleck.yi.org/cgi-bin/LatLongWeather.cgi?Snippet=1&LatLong="+weatherPostQuery();
		$('<div class="popup blue large" id="popupFrame_weather"><div class="closeFrameButton" onclick="$(this).parent().remove();"><img class="closeFrameButtonImg" src="/htmlui/images/icons/sprite-icons-shared3.png"></div><div class="popupFrameTitle">Weather Forecast</div><div id="weatherBody" class="popupFrameBody">Loading weather forecast for current location...</div></div>')
				.appendTo("#contentBody").draggable({handle: ".popupFrameTitle", stack: ".popup"});
			var container = $("#weatherBody").css("overflow-y", "auto");
			containerHTML ? $("#weatherBody").html(containerHTML) : weatherAjax(weatherUrl , container);
	}
	else
	{
		cacheFavoriteCities();
	}
	return false;
}

$(document).ready(function(){
	$("#cityWeather").click(loadWeatherForecast);
});